package com.bifrost.admin.controller;

import com.bifrost.common.util.HttpRequestUtils;
import com.bifrost.entity.IndexSetting;
import com.bifrost.entity.IndexSettingRegion;
import com.bifrost.entity.Media;
import com.bifrost.entity.MerchantStore;
import com.bifrost.model.ResultModel;
import com.bifrost.model.vo.IndexConfigVo;
import com.bifrost.model.vo.IndexSettingVo;
import com.bifrost.model.vo.PageVO;
import com.bifrost.repository.IndexSettingRegionRepository;
import com.bifrost.repository.MerchantStoreRepository;
import com.bifrost.service.IndexSettingRegionService;
import com.bifrost.service.MediaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *   后台首页配置
 *  @Author:Sophia
 *  @Date:2018/4/19
 *  
 */
@RestController
@Api("后台首页配置接口")
@RequestMapping("/admin/index")
public class IndexConfigController {

    private static final Logger LOGGER= LoggerFactory.getLogger(IndexConfigController.class);

    @Autowired
    IndexSettingRegionService indexSettingRegionService;
    @Autowired
    MerchantStoreRepository merchantStoreRepository;
    @Autowired
    IndexSettingRegionRepository indexSettingRegionRepository;
    @Autowired
    MediaService mediaService;

    @ApiOperation("获取所有门店首页配置")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "merchantId",value = "门店ID",dataType = "Long",required = false),
            @ApiImplicitParam(paramType = "query",name = "merchantName",value = "门店名",dataType = "String",required = false),
            @ApiImplicitParam(paramType = "query", name = "page", value = "当前页", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页数量", required = false, dataType = "String")
    })
    @GetMapping("/config/all")
    public ResultModel getIndexConfig(Long merchantId, String merchantName, @RequestParam(value = "page", defaultValue = "1") String page, @RequestParam(value = "pageSize", defaultValue = "10") String pageSize,Boolean visible){
        Page<IndexSettingRegion> data=indexSettingRegionService.findAll(merchantId,merchantName,Integer.parseInt(page),Integer.parseInt(pageSize),visible);
        if (data!=null&&data.hasContent()) {
            List<IndexSettingRegion> list = data.getContent();
            if (CollectionUtils.isNotEmpty(list)){
                List<IndexConfigVo> vos=new ArrayList<>(list.size());
                list.forEach(index->{
                    IndexConfigVo vo=new IndexConfigVo();
                    BeanUtils.copyProperties(index,vo);
                    //TODO 设置其他属性
                    vo.setIndexRegionTitle(index.getIndexRegionTitle()==null?"":index.getIndexRegionTitle());
                    vo.setMerchantId(index.getMerchantStore().getMerchantId());
                    vo.setStoreName(index.getMerchantStore().getStoreName());
                    vos.add(vo);
                });
                if (CollectionUtils.isNotEmpty(vos)){
                    PageVO vo=new PageVO(data.getNumber(),data.getSize(),(int)data.getTotalElements(),vos);
                    return ResultModel.ok("成功").put("config",vo);
                }
            }
        }
        return ResultModel.error("没有满足条件的数据");
    }

    @ApiOperation("新增门店首页配置")
    @PostMapping("/config/add")
    public ResultModel addIndexConfig(@RequestBody IndexConfigVo configVo){
        IndexSettingRegion region=new IndexSettingRegion();
        BeanUtils.copyProperties(configVo,region);
        //TODO 设置其余属性
        if (configVo.getMerchantId()!=null){
            region.setMerchantStore(merchantStoreRepository.findOne(configVo.getMerchantId()));
        }
        IndexSettingRegion indexSettingRegion=indexSettingRegionService.save(region);
        if (indexSettingRegion!=null){
            return ResultModel.ok("成功");
        }
        return ResultModel.error("新增数据失败");
    }

    @ApiOperation("更新门店首页配置")
    @PostMapping("/config/update")
    public ResultModel updateIndexConfig(@RequestBody IndexConfigVo configVo){
        IndexSettingRegion region=new IndexSettingRegion();
        BeanUtils.copyProperties(configVo,region);
        if (configVo.getMerchantId()!=null){
            region.setMerchantStore(merchantStoreRepository.findOne(configVo.getMerchantId()));
        }
        region.setVisible(configVo.getVisible());
        IndexSettingRegion check=indexSettingRegionService.findById(region.getIndexRegionId());
        if (check==null){
            return ResultModel.error("该配置不存在");
        }
        IndexSettingRegion indexSettingRegion=indexSettingRegionService.save(region);
        if (indexSettingRegion!=null){
            return ResultModel.ok("成功");
        }
        return  ResultModel.error("更新数据失败");
    }

    @ApiOperation("删除门店配置信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "ids",value = "配置ID",dataType = "String",required = true)
    })
    @PostMapping("/config/delete")
    public ResultModel deleteIndexConfig(@RequestParam String ids, @RequestParam Long merchantId){
        if (merchantId==null){
            return ResultModel.error("门店不能为空");
        }
        MerchantStore store=merchantStoreRepository.findOne(merchantId);
        if (store==null){
            return ResultModel.error("门店不存在");
        }
        if (StringUtils.isBlank(ids)){
            return ResultModel.error("配置信息不存在");
        }
        if (StringUtils.isNotBlank(ids)) {
            String[] regionIds = ids.split(",");
            ArrayList<Long> indexRegionIds = new ArrayList<>(regionIds.length);
            try {
                Arrays.stream(regionIds).forEach(r -> {
                    indexRegionIds.add(Long.valueOf(r));
                });
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.info("类型转换失败");
            }
            List<IndexSettingRegion> list=indexSettingRegionService.findAllByStoreAndIndexRegionId(store,indexRegionIds);
            if (list.size()!=indexRegionIds.size()){
                return ResultModel.error("门店配置信息不存在");
            }
            indexSettingRegionService.deleteByIdAndStore(indexRegionIds,store);
        }
        return ResultModel.ok("成功");
    }

    @ApiOperation("获取指定门店首页配置")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "indexRegionId",value = "配置ID",dataType = "Long",required = true),
            @ApiImplicitParam(paramType = "query", name = "page", value = "当前页", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页数量", required = false, dataType = "String")
    })
    @GetMapping("/store/config")
    public ResultModel getIndexConfig(String visible ,@RequestParam Long indexRegionId, @RequestParam(value = "page", defaultValue = "1") String page, @RequestParam(value = "pageSize", defaultValue = "10") String pageSize){
        Page<IndexSetting> data=indexSettingRegionService.findByIndexRegionId(visible,indexRegionId,Integer.parseInt(page),Integer.parseInt(pageSize));
        if (data!=null&&data.hasContent()){
            List<IndexSetting> list=data.getContent();
            if (CollectionUtils.isEmpty(list)){
                return ResultModel.error("门店详细配置信息不存在");
            }
            List<IndexSettingVo> vos=new ArrayList<>(list.size());
            list.stream().forEach(s->{
                    IndexSettingVo vo=new IndexSettingVo();
                    vo.setIndexSettingId(s.getIndexSettingId());
                    vo.setDisplayTemplate(s.getDisplayTemplate());
                    if (s.getIndexSettingImg()!=null){
                        vo.setImg(HttpRequestUtils.getUrlAccessPath().concat(s.getIndexSettingImg().getUrl()));
                        vo.setImgId(s.getIndexSettingImg().getMediaId());
                    }
                    vo.setIndexSettingContents(s.getIndexSettingContents());
                    vo.setIndexSettingDescription(s.getIndexSettingDescription());
                    vo.setIndexSettingName(s.getIndexSettingName());
                    vo.setIndexSettingUrl(s.getIndexSettingUrl());
                    vo.setVisible(s.getIsVisible());
                    vo.setSortOrder(s.getSortOrder());
                    vo.setParentId(s.getParentId());
                    vo.setIndexRegionId(s.getIndexSettingRegion().getIndexRegionId());
                    vos.add(vo);
            });
            if (CollectionUtils.isNotEmpty(vos)){
                PageVO vo=new PageVO(data.getNumber(),data.getSize(),(int)data.getTotalElements(),vos);
                return ResultModel.ok("成功").put("config",vo);
            }
        }
        return ResultModel.error("没有满足条件的数据");
    }

    @ApiOperation("新增指定门店首页配置")
    @PostMapping("/store/add")
    public ResultModel addStoreIndexConfig(@RequestBody IndexSettingVo settingVo) throws IOException {
        IndexSetting setting=new IndexSetting();
        BeanUtils.copyProperties(settingVo,setting);
        setting.setIsVisible(settingVo.getVisible());
        //TODO 设置其余属性
        setting.setIndexSettingRegion(indexSettingRegionRepository.findOne(settingVo.getIndexRegionId()));
        Assert.notNull(settingVo.getImgId(),"上传图片不能为空");
        Media media = mediaService.getMediaById(settingVo.getImgId());
        Assert.notNull(settingVo.getImgId(),"上传图片不存在");
        setting.setIndexSettingImg(media);
        IndexSetting indexSetting=indexSettingRegionService.save(setting);
        if (indexSetting!=null){
            return ResultModel.ok("成功");
        }
        return ResultModel.error("新增数据失败");
    }

    @ApiOperation("更新指定门店首页配置")
    @PostMapping("/store/update")
    public ResultModel updateStoreIndexConfig(@RequestBody IndexSettingVo settingVo) throws IOException {
        //判断详细配置信息是否存在
        if (settingVo.getIndexSettingId()==null){
            return ResultModel.error("门店详细配置信息不能为空");
        }
        //判断配置信息是否存在于详细配置中
        List<IndexSetting> checkIndex=indexSettingRegionService.finfByIndexRegionId(indexSettingRegionRepository.findOne(settingVo.getIndexRegionId()));
        if (CollectionUtils.isEmpty(checkIndex)){
            return ResultModel.error("门店详细配置不存在");
        }
        IndexSetting setting=new IndexSetting();
        BeanUtils.copyProperties(settingVo,setting);
        //TODO 设置其他属性
        setting.setIndexSettingRegion(indexSettingRegionRepository.findOne(settingVo.getIndexRegionId()));
        setting.setIsVisible(settingVo.getVisible());
        //检查门店详细配置是否存在
        IndexSetting checkSetting=indexSettingRegionService.findByIndexSettingId(setting.getIndexSettingId());
        if (checkSetting==null){
            return ResultModel.error("门店详细配置信息不存在");
        }
        if (!settingVo.getIndexRegionId().equals(checkSetting.getIndexSettingRegion().getIndexRegionId())){
            return ResultModel.error("门店配置信息与详细配置信息不一致");
        }
        Assert.notNull(settingVo.getImgId(),"上传图片不能为空");
        Media media = mediaService.getMediaById(settingVo.getImgId());
        Assert.notNull(settingVo.getImgId(),"上传图片不存在");
        setting.setIndexSettingImg(media);
        IndexSetting indexSetting=indexSettingRegionService.save(setting);
        if (indexSetting!=null){
            return ResultModel.ok("成功");
        }
        return ResultModel.error("更新数据失败");
    }


    @ApiOperation("删除指定门店首页配置")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "indexSettingIds",value = "详细配置ID",dataType = "String",required = true)
    })
    @PostMapping("/store/delete")
    public ResultModel deleteStoreIndexConfig(@RequestParam Long indexRegionId, @RequestParam String indexSettingIds){
        if (indexRegionId==null){
            return ResultModel.error("门店配置不能为空");
        }
        if (StringUtils.isBlank(indexSettingIds)){
            return ResultModel.error("门店详细配置不能为空");
        }
        //判断配置信息是否存在于详细配置中
        List<IndexSetting> indexSettings=indexSettingRegionService.finfByIndexRegionId(indexSettingRegionRepository.findOne(indexRegionId));
        if (CollectionUtils.isEmpty(indexSettings)){
            return ResultModel.error("门店详细配置不存在");
        }
        String[] settingIds=indexSettingIds.split(",");
        ArrayList<Long> ids=new ArrayList<>(settingIds.length);
        try {
            Arrays.stream(settingIds).forEach(setting->{
                ids.add(Long.valueOf(setting));
            });
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("类型转换失败");
        }
        for(int i=0;i<ids.size();i++){
            IndexSetting setting=indexSettingRegionService.findByIndexSettingIdAndIndexSettingRegion(ids.get(i),indexSettingRegionRepository.findOne(indexRegionId));
              if (setting==null){
                  return ResultModel.error("门店详细配置信息不存在");
              }
        }
        indexSettingRegionService.deleteByIndexSettingId(ids);
        return ResultModel.ok("成功");
    }

}
